const dbExec = require('../postgreDB/config');

//1、安装ws模块 npm install ws
//2、导入ws模块
const WebSocket=require('ws');
//3、创建WebSocket服务器
const server=new WebSocket.Server({port:8084});
//4、监听open事件
server.on('open',()=>{
    console.log('建立连接');
})
//5、绑定close事件
server.on('close',()=>{
    console.log('关闭连接')
})
//6、绑定connection事件 ws参数表示客户端 req表示客户端的请求信息
server.on('connection',(ws,req)=>{
    //6.1获取客户端的ip port
    const ip=req.connection.remoteAddress;
    const port=req.connection.remotePort;
    const clientName=ip+port;
    console.log('%s is connect',port);
    
    //6.2向客户端发送消息
    // ws.send('欢迎'+clientName);
    //监听 客户端 message 事件，转发给其他人
    ws.on('message',async(msg)=>{
        let data = JSON.parse(msg.toString());
        console.log(data.type)
        if(data.type=='open'){
            let table = await dbExec(`select * from rooms where room='${data.room}'`);
            let room = table.rows[0];
            let p = '';
            if(room.userid1==data.userId)p='port1';
            else if(room.userid2==data.userId)p='port2';
            await dbExec(`update rooms set ${p}='${port}' where room='${data.room}'`)
            server.clients.forEach((client)=>{
                //若某个客户端是打开的，就把消息广播给该客户
                if (client.readyState===WebSocket.OPEN&&client._socket._peername.port==port){
                    if(p=='port1')
                        client.send(JSON.stringify({type:'open',player:room.userid1>room.userid2?1:2})); 
                    else if(p=='port2')
                        client.send(JSON.stringify({type:'open',player:room.userid1>room.userid2?2:1})); 
                }
            })
        }else if(data.type=='drop'){
            let table = await dbExec(`select * from rooms where room='${data.room}'`);
            let room = table.rows[0];
            let p = '';
            if(room.port1==port)p=room.port2;
            else if(room.port2==port)p=room.port1;
            server.clients.forEach(function (client) {
                if (client.readyState===WebSocket.OPEN&&client._socket._peername.port==p){
                    client.send(JSON.stringify({type:'drop',arr:data.arr})); 
                }
            })
        }
    })
})